﻿using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Sirenix.OdinInspector;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ActiveMQMain : MonoBehaviour
{

	#region 字段属性

	// ==== 审查元素 ==== //

	public string urlPost = "tcp://127.0.0.1:61618/";
    public List<string> topic_List = new List<string>();//主题列表
    public Button sendBtn;
    ISession session;

    static IMessageProducer mesProd;//SCADA所属
    static ITextMessage mesMessage;//SCADA消息
    #endregion

	#region 生命周期
	private void Start()
    {
        //_mqConnection = Simulator.Comm.Communication.Inerface.ConnectionFactory.GetConnection();//获取连接
        //sendBtn.onClick.AddListener(() =>
        //{
        //    SendMessage();
        //});

        CreateConnector();
    }
    #endregion

	#region 私有方法-创建连接

	/// <summary>
	/// 创建连接
	/// </summary>
	private void CreateConnector()
    {
        try
        {
            IConnectionFactory factory = new ConnectionFactory(urlPost);//连接
            IConnection connection = factory.CreateConnection();//创建消费者
            connection.ClientId = "testing listener";
            connection.Start();
            ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge);//创建会话
            //创建持久消费者
            IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"),
                "testing listener", null, false);//SCADA消息监听通道
            consumer.Listener += new MessageListener(RescuedMessage);

            IMessageConsumer _JLC = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("ReadSCADATop"),
                "readScada", null, false);//SCADA主动获取数据通道（与监听通道一起会造成阻塞）
            _JLC.Listener += new MessageListener(JLCResourcesMessage);

            IMessageConsumer mes_Asc = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("MesAscTop"),
               "mesAscClient", null, false);//SCADA主动获取数据通道（与监听通道一起会造成阻塞）
            mes_Asc.Listener += new MessageListener(JLCResourcesMessage);

            IMessageConsumer steffCons = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("Staffing"),
                "StaffMessage", null, false);//人员定位通道
            steffCons.Listener += new MessageListener(StaffDataResvercesMessage);

            //Create the Producer for the topic/queue  
            mesProd = session.CreateProducer(
                new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("MESRequest"));//mes请求发送通道
            mesMessage = mesProd.CreateTextMessage();
            Debug.Log("ActiveMQ连接器，连接成功");
        }
        catch (Exception e)
        {
            Debug.Log("ActiveMQ连接器，连接失败：" + e.Message);
        }

        //IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");
        ////通过工厂构建连接
        //IConnection connection = factory.CreateConnection();
        ////这个是连接的客户端名称标识
        //connection.ClientId = "firstQueueListener";
        ////启动连接，监听的话要主动启动连接
        //connection.Start();
        ////通过连接创建一个会话
        //ISession session = connection.CreateSession();
        ////通过会话创建一个消费者，这里就是Queue这种会话类型的监听参数设置
        //IMessageConsumer consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("firstQueue"), "filter='demo'");
        ////注册监听事件
        //consumer.Listener += new MessageListener(RescuedMessage);
        //Debug.Log("ActiveMQ连接器，连接成功");
    }

	/// <summary>
	/// 创建订阅者
	/// </summary>
	/// <param name="TopicStr"></param>
	/// <returns></returns>
	IMessageConsumer CreaeDurable (string TopicStr)
    {
        ITopic itopic = session.GetTopic(TopicStr);
        return session.CreateDurableConsumer(itopic, "testing listener1", null, false);
    }

    #endregion

	#region 公开方法

	public void SendMessage()
    {
        try
        {
            //Create the Connection Factory  
            IConnectionFactory factory = new ConnectionFactory("tcp://127.0.0.1:61618/");
            //IConnectionFactory factory = new ConnectionFactory("tcp://0.0.0.0:8161/");
            using (IConnection connection = factory.CreateConnection())
            {
                //Create the Session  
                using (ISession session = connection.CreateSession())
                {
                    //Create the Producer for the topic/queue  
                    IMessageProducer prod = session.CreateProducer(
                        new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("TrainControl"));

                    //Send Messages  
                    int i = 0;


                    ITextMessage msg = prod.CreateTextMessage();
                    msg.Text = i.ToString();
                    Console.WriteLine("Sending: " + i.ToString());
                    prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue);

                    //System.Threading.Thread.Sleep(5000);
                    //i++;
                }
            }

            Console.ReadLine();
        }
        catch (System.Exception e)
        {
            Console.WriteLine("{0}", e.Message);
            Console.ReadLine();
        }
    }

    //public class MessageReader<T>
    //{
    //    private readonly IConsumerSession _reader;//消息消费者

    //    /// <summary>
    //    /// 
    //    /// </summary>
    //    /// <param name="connection"></param>
    //    /// <param name="topicName">消息主题名称</param>
    //    public MessageReader(IMqConnection connection, string topicName)
    //    {
    //        _reader = connection.GetConsumerSession(topicName, null, true, false);//获取消费者会话
    //        _reader.SetMessageListener(OnMessage);//设置消息监听器
    //    }

    //    private void OnMessage(IMessage message)
    //    {
    //        if (!message.Properties.Contains("simuTimestamp"))
    //            throw new CommunicationException("消息中未设置模拟时间属性", null);

    //        long tick = (long)message.Properties["simuTimestamp"];//消息时间戳
    //        string station = (string)message.Properties["station"];//消息

    //        IBytesMessage bytesMessage = (IBytesMessage)message;

    //        Debug.Log(message.NMSType);
    //    }

    //}

    public void RescuedMessage(IMessage message)
    {
        //Debug.Log(message.ToString());
        //Debug.Log(((ITextMessage)message).Text.ToString());
        message.Acknowledge();//消息确认消费
        StrTool(((ITextMessage)message).Text);
    }

    public void JLCResourcesMessage(IMessage message) //精铝槽主动获取数据主题方法
    {

        message.Acknowledge();
        StrReadTool(((ITextMessage)message).Text);
    }

    public void MES_AscDataMessage(IMessage message)
    {
        message.Acknowledge();
        AcknowReadTool(((ITextMessage)message).Text);
    }

	/// <summary>
	/// 人员定位消息
	/// </summary>
	/// <param name="message"></param>
	public void StaffDataResvercesMessage(IMessage message)
    {
        message.Acknowledge();
        Debug.Log("StaffData：" + (((ITextMessage)message).Text));
    }

    string[] levelStrArr;
    string[] workStrArr;
    void StrTool(string str) 
    {
        
        levelStrArr = str.Split('~');//整体拆分消息
        workStrArr = levelStrArr[0].Split('0');//拆分句柄

        //判断车间
        if (workStrArr[0] == "1")//原料车间
        {
            EventManagers._OPCDAMQReceiveChangeYL_Text_event?.Invoke(levelStrArr);
        }
        else if (workStrArr[0] == "2")//精铝车间
        {
            EventManagers._OPCDAMQReceiveChangeJL_Text_event?.Invoke(levelStrArr);
        }
        else if (workStrArr[0] == "3")
        {
            EventManagers._OPCDAMQReceiveChangeZZ_Text_event?.Invoke(levelStrArr);
            EventManagers._OPCDAMQReceiveChangeZZDeciveMonitoring?.Invoke(workStrArr[1], levelStrArr);
        }
        else if (workStrArr[0] == "4")
        {
            EventManagers._OPCDAMQReceiveChangeKY_Text_event?.Invoke(levelStrArr);
            EventManagers._OPCDAMQReceiveChangeKYDeciveMonitoring?.Invoke(workStrArr[1], levelStrArr);
        }
        else if (workStrArr[0] == "5") 
        {
            EventManagers._OPCDAMQReceiveChangeSW_Text_event?.Invoke(levelStrArr);
        }
    }


    string[] ackMESArry;
    void AcknowReadTool(string str)
    {
        ackMESArry = str.Split('~');

    }

    string[] readStrArr;
    void StrReadTool(string str)
    {
        Debug.Log("JLCResources：" + str);
        EventManagers._OPCDAMQReceiveReadStr_Text_event?.Invoke(str.Split('~'));
    }


    [Button("发送请求", ButtonSizes.Large, Style = ButtonStyle.Box),]
    public void SendResqurstMES(string str) //主动发送EMS数据请求
    {
        ActiveMQSend(mesMessage, mesProd, str);
    }

    void ActiveMQSend(ITextMessage message, IMessageProducer messageProducer, string str)
    {
        message.Text = str;
        messageProducer.Send(message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue);
        Console.WriteLine("消息已发送：" + str);
    }

	#endregion

}
